<?php
include_once 'plugin/ExpressLocation.php';
class ajaxController extends commonController
{
    public function getOrderProductAction()
    {
        $table = 'orders';
        $id = (!empty($this->params['id'])) ? (int)$this->params['id'] : '';
        $orderInfo = $this->model->getItemById($id,$table);
        if (!empty($orderInfo) && count($orderInfo)>0) {
            $where = array("AND" => array("=" => array("ph_no" => $orderInfo['ph_no'],"status" => 1,"isdeleted" => 0)));
            $orderby = array('id'=>'asc');
            $column_fields = 'product_name,id,weight';
            $products = $this->model->getAll($where, 'orders_product', $orderby,$column_fields);
        }
        echo json_encode($products);
    }


    public function getLocationAction()
    {
        $shop_no = (!empty($this->params['shop_no'])) ? $this->params['shop_no'] : '';
        $express_order_no = (!empty($this->params['express_order_no'])) ? $this->params['express_order_no'] : '';
        $express_type = (!empty($this->params['express_type'])) ? $this->params['express_type'] : '';
        $order_no = (!empty($this->params['shop_express_no'])) ? $this->params['shop_express_no'] : '';
        $status = (!empty($this->params['status'])) ? $this->params['status'] : '';



        $config = Config::getInstance();
        $website_array = $config->getWebSiteConfig();
        $result = ['status'=>'error','msg'=>'','data'=>''];
        $whereR = array("AND" => array("=" => array('store_id'=>$shop_no, "isdeleted"=>0)));
        $shop_no_info = $this->model->getItemByOther($whereR,'xd_store');
        if($status == 5){
            $r['slng'] = $shop_no_info[0]['longitude'];
            $r['slat'] = $shop_no_info[0]['latitude'];
            $result['data'] = $r;
            $result['status'] = 'success';
            echo json_encode($result);
            exit;
        }

        if($shop_no && is_array($shop_no_info) && count((array) $shop_no_info) > 0){

            $whereR = array("AND" => array("=" => array('code'=>$shop_no_info[0]['company_id'], "isdeleted"=>0)));
            $xd_company = $this->model->getItemByOther($whereR,'xd_company');
            $storeData = [];
            $storeData['user365Id'] = $shop_no_info[0]['user365Id'];
            $storeData['shop_no'] = $shop_no;
            $storeData['debug'] = $website_array['debug'];
            $storeData['express_order_no'] = $express_order_no;
//            $storeData['express_order_no'] = '20121110433057958855';
            $storeData['express_type'] = $express_type;
            $storeData['order_no'] = $order_no;

            $storeData['sf_dev_id'] = $xd_company[0]['sf_dev_id'];
            $storeData['sf_user_name'] = $xd_company[0]['sf_user_name'];
            $storeData['sf_dev_key'] = $xd_company[0]['sf_dev_key'];

            $storeData['uu_app_id'] = $shop_no_info[0]['uu_app_id'];
            $storeData['uu_app_key'] = $shop_no_info[0]['uu_app_key'];
            $storeData['uu_open_id'] = $shop_no_info[0]['uu_open_id'];

            $storeData['ss_clientId'] = $shop_no_info[0]['ss_clientId'];
            $storeData['ss_clientSecret'] = $shop_no_info[0]['ss_clientSecret'];
            $storeData['ss_shopId'] = $shop_no_info[0]['ss_shopId'];

            $storeData['dd_source_id'] = $shop_no_info[0]['dd_source_id'];
            $storeData['dd_app_key'] = $shop_no_info[0]['dd_app_key'];
            $storeData['dd_app_secret'] = $shop_no_info[0]['dd_app_secret'];

            $storeData['jrd_sign'] = $shop_no_info[0]['jrd_sign'];

        }else{
            $result['status'] = 'error';
            $result['msg'] = '门店资料异常';
        }
        $r['errorcode'] = 'fail';
        $location = new GetExpressLocation();
        $r = $location->get_result((array)$storeData,$this->model);

//        if(!$result['msg'] || $result['msg'] == 'null') $result['msg'] = '当前快递不支持骑手位置查询';
//        echo '<pre>';
//        var_dump($r);die;
        if($r && $r['errorcode'] == 0){
            unset($r['errorcode']);
            $slng = $slat = '';
            if(strtolower($express_type) == 'ss' || strtolower($express_type) == 'uu'){
                $slng = $shop_no_info[0]['longitude'];
                $slat = $shop_no_info[0]['latitude'];
            }else{
                $StoreAddress = $shop_no_info[0]['front_province']. $shop_no_info[0]['front_city']. $shop_no_info[0]['front_area']. $shop_no_info[0]['front_address'];
                $o = $this->EXGold($StoreAddress);
                if($o && count((array)$o) > 0){
                    $slng = $o[0];
                    $slat = $o[1];
                }
            }
            $r['slng'] = $slng;
            $r['slat'] = $slat;
            $result['data'] = $r;
            $result['status'] = 'success';
        }else{
            $result['status'] = 'error';
            $result['msg'] = $r['msg'];
        }
        if(!$r['exp_lat'] || !$r['exp_lng']) {
            $r['status'] = 'error';
            $r['msg'] = Data::$_express_type[$express_type].'回调资料异常';
        }

        echo json_encode($result);
    }

    public function delOrdersAction(){
        $list = (!empty($this->params['list'])) ? $this->params['list'] : '';
        $r_del = (!empty($this->params['r_del'])) ? $this->params['r_del'] : '';
        $renew = (!empty($this->params['renew'])) ? $this->params['renew'] : '';
        $rt = ['status'=>'success','msg'=>'删除成功','error_ids'=> [],'success_ids'=> []];
        $field = [];
        $field['updatedt'] = 'now()';
        $field["update_id"] = $_SESSION['zp_shop']['store_id'];
        if($renew == 'renew'){
            $field['isdeleted'] = $field['status'] = 0;
            $field['renew'] = $r_del;
            $field['del_t'] = 999;
            $where_fields = array("AND" => array("=" => array('id' => $list[0])));
            $this->model->updateItem($field, $where_fields, 'orders');
            $rt['success_ids'][0] = $list[0];
            $rt['msg'] = '恢复成功';
        }else{
            $field['isdeleted'] = 1;
            $field['status'] = 100; # 标记恢复
            $field['renew'] = '';
            $field['del_t'] = $r_del;
            try {
                foreach ($list as $k => $itm){
                    $orderInfo = $this->model->getItemById($itm,'orders');
                    $edit = [];
                    $edit['updatedt']= 'now()';
                    $edit['isdeleted'] = 1;
                    $where_express = array("AND" => array("=" => array('order_no' => $orderInfo['order_no'])));
                    $this->model->updateItem($edit, $where_express, 'express_data');
                    $this->model->updateItem($edit, $where_express, 'orders_express');


                    $where_fields = array("AND" => array("=" => array('id' => $itm)));
                    $r = $this->model->updateItem($field, $where_fields, 'orders');
                    if($r){
                        $rt['success_ids'][$k] = $itm;
                    }else{
                        $rt['error_ids'][$k] = $itm;
                    }
                }
            } catch (Exception $e) {
                $rt['status'] = 'error';
                $rt['msg'] = '系统异常，稍后重试';

            }
        }

        echo json_encode($rt);
    }


    # 兑换高德经纬度
    private function EXGold($address){
        include_once ('plugin/GaoDeAPIClass.php');
        $log = new Logging();
        $log->lfile('EXGold');
        if(strstr($address,'(')){
            $address = strstr($address,'(',true);
        }
        if(strstr($address,'（')){
            $address = strstr($address,'（',true);
        }

        $address = str_replace(' ','',$address);
        $log->lwrite(date('Y-m-d H:i:s').'  ad：'.$address.'');
        $GaoDeAPI = new GaoDeAPI();
        $r = $GaoDeAPI->getTrapezeAction($address);
        $location = [];
        if($r && count($r) > 0){
            $location = explode(',',$r['geocodes'][0]['location']);
        }
        $log->lwrite(date('Y-m-d H:i:s').'  res：'.json_encode($location,JSON_UNESCAPED_UNICODE).'');
        if($location && is_array($location) && count($location) > 1){
            return $location;
        }else{
            return '';
        }

    }


    public function ExpressLocationAction()
    {
        $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
        $Config = Config::getInstance();
        $webSite = $Config->getWebSiteConfig();
        $url = substr($webSite['wx_url'],0,strrpos($webSite['wx_url'],'/'));
        $file = 'order_system';
        $allow_origin = [
            $url,
        ];
        if(in_array($origin, $allow_origin)){
            header('Access-Control-Allow-Origin:'.$origin);
        }
        $str = base64_decode($this->params['str']);
        $Data['check_code'] = substr($str,0,16);
        $Data['wx_order_no'] = substr($str,16);
        if(base64_encode($Data['check_code'].$Data['wx_order_no']) != $this->params['str']){
            self::WriteResponse($file,0,'参数有误','');
        }

        self::WriteReception($file,$str);
        $validate = ['check_code'=>'check','wx_order_no'=>'string'];
        self::Verify($Data,$validate,$file,Data::$VERSION);

        $config = Config::getInstance();
        $website_array = $config->getWebSiteConfig();


        $result = ['status'=>'fail','msg'=>'','data'=>''];
        $whereO = array("AND" => array("=" => array('wx_orderNo'=>$Data['wx_order_no'], "isdeleted"=>0)));
        $orders = $this->model->getItemByOther($whereO,'orders');

        if(empty($orders[0]) || count((array) $orders[0])  <1){
            $result['msg'] = '订单不存在';
            echo json_encode($result);
            exit;
        }
        $whereOE = array("AND" => array("=" => array('ph_no'=>$orders[0]['ph_no'], "isdeleted"=>0, "status"=>$orders[0]['status'])));
        $orders_express = $this->model->getItemByOther($whereOE,'orders_express');

        if(empty($orders_express[0]) || count((array) $orders_express[0])  <1){
            $result['msg'] = '订单不存在';
            echo json_encode($result);
            exit;
        }
        $express_order_no = $orders_express[0]['express_order_no'];
        $express_type = $orders_express[0]['express_type'];
        $order_no = $orders_express[0]['order_no'];


        $whereR = array("AND" => array("=" => array('store_id'=>$orders[0]['shop_no'], "isdeleted"=>0)));
        $shop_no_info = $this->model->getItemByOther($whereR,'xd_store');
        if(empty($shop_no_info[0]) || count((array) $shop_no_info[0])  <1){
            $result['msg'] = '配送门店信息异常';
            echo json_encode($result);
            exit;
        }

        $whereR = array("AND" => array("=" => array('code'=>$shop_no_info[0]['company_id'], "isdeleted"=>0)));
        $xd_company = $this->model->getItemByOther($whereR,'xd_company');
        $storeData = [];
        $storeData['user365Id'] = $shop_no_info[0]['user365Id'];
        $storeData['shop_no'] = $orders[0]['shop_no'];
        $storeData['debug'] = $website_array['debug'];
        $storeData['express_order_no'] = $express_order_no;
//            $storeData['express_order_no'] = '20121110433057958855';
        $storeData['express_type'] = $express_type;
        $storeData['order_no'] = $order_no;

        $storeData['sf_dev_id'] = $xd_company[0]['sf_dev_id'];
        $storeData['sf_user_name'] = $xd_company[0]['sf_user_name'];
        $storeData['sf_dev_key'] = $xd_company[0]['sf_dev_key'];

        $storeData['uu_app_id'] = $shop_no_info[0]['uu_app_id'];
        $storeData['uu_app_key'] = $shop_no_info[0]['uu_app_key'];
        $storeData['uu_open_id'] = $shop_no_info[0]['uu_open_id'];

        $storeData['ss_clientId'] = $shop_no_info[0]['ss_clientId'];
        $storeData['ss_clientSecret'] = $shop_no_info[0]['ss_clientSecret'];
        $storeData['ss_shopId'] = $shop_no_info[0]['ss_shopId'];

        $storeData['dd_source_id'] = $shop_no_info[0]['dd_source_id'];
        $storeData['dd_app_key'] = $shop_no_info[0]['dd_app_key'];
        $storeData['dd_app_secret'] = $shop_no_info[0]['dd_app_secret'];

        $storeData['jrd_sign'] = $shop_no_info[0]['jrd_sign'];



        $r['errorcode'] = 'fail';
        $location = new GetExpressLocation();
        $r = $location->get_result((array)$storeData,$this->model);

        if($r && $r['errorcode'] == 0){
            unset($r['errorcode']);
            $slng = $slat = '';
            if(strtolower($express_type) == 'ss' || strtolower($express_type) == 'uu'){
                $slng = $shop_no_info[0]['longitude'];
                $slat = $shop_no_info[0]['latitude'];
            }else{
                $StoreAddress = $shop_no_info[0]['front_province']. $shop_no_info[0]['front_city']. $shop_no_info[0]['front_area']. $shop_no_info[0]['front_address'];
                $o = $this->EXGold($StoreAddress);
                if($o && count((array)$o) > 0){
                    $slng = $o[0];
                    $slat = $o[1];
                }
            }
            $r['slng'] = $slng;
            $r['slat'] = $slat;
            $r['express_type'] = $express_type;
            $r['express_courier'] = $orders_express[0]['express_courier'];
            $r['express_mobile'] = $orders_express[0]['express_mobile'];
            $r['status'] = $orders_express[0]['status'];
            $result['data'] = $r;
            $result['status'] = 'success';
        }else{
            $result['status'] = 'error';
            $result['msg'] = $r['msg'];
        }
        if(!$r['exp_lat'] || !$r['exp_lng']) {
            $r['status'] = 'error';
            $r['msg'] = Data::$_express_type[$express_type].'回调资料异常';
        }
        echo json_encode($result);
    }
}

